import React, { useRef, useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { AppBar, Toolbar, Box, IconButton, Typography, styled } from '@mui/material';
import DragHandleIcon from '@mui/icons-material/DragHandle';
import PortalDraghandleButton from 'components/atoms/PortalDraghandleButton';
import LogoComponent from 'components/atoms/LogoComponent';
import { useDarkMode } from 'contexts/DarkMode';
import { useDrawer } from 'contexts/DrawerContext';
import backgroundImage from 'images/backgroundLoader.gif';

// Styled AppBar component with conditional background based on route
const StyledAppBar = styled(AppBar)(({ isHomePage }) => ({
  background: isHomePage ? 'transparent' : undefined,
  marginTop: 0,
  boxShadow: isHomePage ? 'none' : undefined,
}));

const TopIcons = ({ isXs, isHomePage: propsIsHomePage, useTheme }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const { darkMode } = useDarkMode();
  const { drawerOpen, toggleDrawer } = useDrawer();
  
  // Check if we're on the home page
  const isHomePage = location.pathname === '/home-page';
  
  const [showFixedButton, setShowFixedButton] = useState(false);
  const [showIconButton, setShowIconButton] = useState(true);
  const [isLogoFixed, setIsLogoFixed] = useState(false);
  const [buttonCoords, setButtonCoords] = useState({ right: 0 });
  
  const toolbarRef = useRef(null);
  const dragHandleRef = useRef(null);
  
  const calculatePosition = () => {
    if (dragHandleRef.current) {
      const rect = dragHandleRef.current.getBoundingClientRect();
      const viewportWidth = window.innerWidth;
      const right = viewportWidth - rect.right;
      setButtonCoords({ right });
    }
  };
  
  const handleScroll = () => {
    const scrollY = window.scrollY;
    const toolbarBottom = toolbarRef.current ? toolbarRef.current.getBoundingClientRect().bottom : 0;
    
    const nowScrolledDown = scrollY > 0 && toolbarBottom <= 0;
    
    if (nowScrolledDown) {
      setShowFixedButton(true);
      setShowIconButton(false);
      setIsLogoFixed(true);
      calculatePosition();
    } else {
      setShowFixedButton(false);
      setShowIconButton(true);
      setIsLogoFixed(false);
    }
  };
  
  useEffect(() => {
    calculatePosition();
    window.addEventListener('scroll', handleScroll);
    window.addEventListener('resize', calculatePosition);
    
    return () => {
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('resize', calculatePosition);
    };
  }, []);
  
  // eslint-disable-next-line
  const navigatePage = (url) => {
    window.open(url, '_blank', 'noopener,noreferrer');
  };

  const navigateOpen = (path) => {
    if (path === 'toggleDrawer') {
      toggleDrawer();
    } else {
      navigate(path);
    }
  };
  
  // AppBar component with the same structure and props as before
  const appBarContent = (
    <StyledAppBar 
      position="static" 
      elevation={0} 
      color="transparent" 
      isHomePage={isHomePage}
    >
      <Toolbar ref={toolbarRef} sx={{ 
        display: 'flex', 
        justifyContent: 'space-between',
        padding: { xs: '0.5rem 1rem', md: '0.5rem 2rem' },
        width: '100%'
      }}>
        {/* Logo Component on the left */}
        <LogoComponent 
          darkMode={darkMode} 
          isHomePage={isHomePage} 
          navigateOpen={() => navigateOpen('/')}
          logoText='startersaas.pro'
          isFixed={isLogoFixed}
        />
        
        {/* DragHandle IconButton on the right */}
        {showIconButton && (
          <IconButton 
            ref={dragHandleRef}
            color="primary"
            aria-label="menu"
            onClick={() => toggleDrawer()}
            id="draghandle"
            className="my-custom-class"
            sx={{
              backgroundColor: darkMode ? 'rgba(30, 30, 30, 0.8)' : 'rgba(255, 255, 255, 0.8)',
              boxShadow: '0 2px 8px rgba(0, 0, 0, 0.2)',
              transition: 'all 0.2s ease',
              '&:hover': {
                backgroundColor: darkMode ? 'rgba(40, 40, 40, 0.9)' : 'rgba(245, 245, 245, 0.9)',
                boxShadow: '0 4px 10px rgba(0, 0, 0, 0.3)',
              },
              '&:active': {
                transform: 'scale(0.95)',
              }
            }}
          >
            <DragHandleIcon sx={{
              color: darkMode ? '#fff' : '#333',
              fontSize: '1.5rem'
            }} />
          </IconButton>
        )}
      </Toolbar>
    </StyledAppBar>
  );
  
  // Conditional rendering based on route
  if (isHomePage) {
    return (
      <Box
        sx={{
          height: '100vh',
          backgroundImage: `url(${backgroundImage})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          backgroundRepeat: 'no-repeat',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'space-between',
          width: '100%'
        }}
      >
        {/* AppBar at the top with same structure */}
        {appBarContent}
        
        {/* Typography at the bottom */}
        <Box 
          sx={{ 
            marginBottom: '4rem',
            textAlign: 'center',
            padding: '0 1rem'
          }}
        >
          <Typography 
            variant="h3" 
            component="h1" 
            sx={{ 
              fontWeight: 'bold', 
              color: 'white',
              marginBottom: '1rem'
            }}
          >
            Premium FSBO Leads for Agents
          </Typography>
          <Typography 
            variant="h4" 
            component="h2" 
            sx={{ 
              fontWeight: 'bold', 
              color: 'white'
            }}
          >
            Launch Your Property Listing Referral Today
          </Typography>
        </Box>
        
        {/* Portal Button that appears when scrolled down (outside toolbar) */}
        {!showIconButton && showFixedButton && (
          <PortalDraghandleButton 
            isOpen={drawerOpen}
            onToggle={() => toggleDrawer()}
            id="draghandle-fixed" 
            className="my-custom-class"
            darkMode={darkMode}
            style={{
              position: "fixed",
              top: 10,
              right: `${buttonCoords.right}px`,
              transform: "translateZ(0)",
              willChange: "transform",
              zIndex: 1300,
            }}
          />
        )}
      </Box>
    );
  }
  
  // Default rendering for non-home pages
  return (
    <>
      {appBarContent}
      
      {/* Portal Button that appears when scrolled down (outside toolbar) */}
      {!showIconButton && showFixedButton && (
        <PortalDraghandleButton 
          isOpen={drawerOpen}
          onToggle={() => toggleDrawer()}
          id="draghandle-fixed" 
          className="my-custom-class"
          darkMode={darkMode}
          style={{
            position: "fixed",
            top: 10,
            right: `${buttonCoords.right}px`,
            transform: "translateZ(0)",
            willChange: "transform",
            zIndex: 1300,
          }}
        />
      )}
    </>
  );
};

export default TopIcons;